package com.sskj.common.base;

import android.content.Context;
import android.support.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.annotation.GlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.cache.ExternalPreferredCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.AppGlideModule;
import com.bumptech.glide.request.RequestOptions;
import com.sskj.common.http.SSLSocketFactoryCompat;

import java.io.InputStream;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;

/**
 * @author吕志豪 .
 * @date 18-1-6  下午1:43.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */
@GlideModule
public class MainAppGlideModule extends AppGlideModule {

    private static final int M = 1024 * 1024;
    private static final int MAX_DISK_CACHE_SIZE = 256 * M;
    @Override
    public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
        try {
            // 自定义一个信任所有证书的TrustManager，添加SSLSocketFactory的时候要用到
            final X509TrustManager trustAllCert =
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    };
            final SSLSocketFactory sslSocketFactory = new SSLSocketFactoryCompat(trustAllCert);
            OkHttpClient okhttpClient = new OkHttpClient.Builder()
                    .retryOnConnectionFailure(true) // 设置出现错误进行重新连接。
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
                    .sslSocketFactory(sslSocketFactory,trustAllCert)
                    .hostnameVerifier(new HttpsUtil.UnSafeHostnameVerifier())
                    .build();
            registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okhttpClient));

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public boolean isManifestParsingEnabled() {
        return false;
    }
    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        //设置内存缓存大小
        builder.setMemoryCache(new LruResourceCache(20 * M));
        //设置磁盘缓存目录及大小
        final String cachedDirName = "glide";
        builder.setDiskCache(new ExternalPreferredCacheDiskCacheFactory(context,
                cachedDirName, MAX_DISK_CACHE_SIZE));
        builder.setDefaultRequestOptions(
                new RequestOptions()
                        .format(DecodeFormat.PREFER_RGB_565)
                        .disallowHardwareConfig());
    }
}
